package com.sgb.kjwl.view.ui.adapter;

import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;

import com.sgb.kjwl.model.entity.chat.NewsMenuEntity;

import java.util.List;

public class NewsPagerAdapter extends FragmentStatePagerAdapter {

    private FragmentManager fm;
    private List<? extends Fragment> items;
    private List<NewsMenuEntity> list;

    public NewsPagerAdapter(@NonNull FragmentManager fm, List<? extends Fragment> items, List<NewsMenuEntity> list) {
        super(fm);
        this.fm = fm;
        this.items = items;
        this.list = list;
    }

    @NonNull
    @Override
    public Fragment getItem(int position) {
        return items.get(position);
    }

    @Override
    public int getCount() {
        return items == null ? 0 : items.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        if (list != null && list.size() <= position) return "";
        return list.get(position).getName();
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        Fragment fragment = (Fragment) super.instantiateItem(container,
                position);
        fm.beginTransaction().show(fragment).commitAllowingStateLoss();
        return fragment;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        Fragment fragment = (Fragment) object;
        fm.beginTransaction().hide(fragment).commitAllowingStateLoss();
    }
}
